const response = require('../../utils/response');
const { handleDatabaseError } = require('../../utils/dberrordeal');
const shopCarService = require('../../services/good/shopCarService');
class ShopCarController {
    static async getShopCarList(ctx) {
        try {
            // 初始化请求数据
            const requestData = ctx.request.body || {};
            
            // 设置分页参数默认值
            const pageNum = parseInt(requestData.pageNum) || 1;
            const pageSize = parseInt(requestData.pageSize) || 10;
            
            // 构建查询数据，排除分页参数
            const queryData = { ...requestData };
            delete queryData.pageNum;
            delete queryData.pageSize;
            
            // 设置用户ID
            queryData.userId = ctx.userId;
            
            const res = await shopCarService.getShopCarList({ pageNum, pageSize }, queryData);
            response.success(ctx, { data: res });
        } catch (err) {
            handleDatabaseError(ctx, err, '获取购物车列表失败');
        }
    }
    static async getShopCarById(ctx) {
        const { id: shopCarId } = ctx.request.body;
        console.log(shopCarId);
        const res = await shopCarService.getShopCarById(shopCarId);
        res ? response.success(ctx, { data: res }) : response.error(ctx, {message: '购物车不存在'});
    }
    static async createShopCar(ctx) {
        try {
            const shopCarData = ctx.request.body;
            
            // 验证必要字段
            if (!shopCarData.goodId || !shopCarData.sid) {
                return response.error(ctx, { message: '缺少必要的商品信息' });
            }
            
            // 验证商品数量
            const quantity = parseInt(shopCarData.quantity) || 1;
            if (quantity <= 0) {
                return response.error(ctx, { message: '商品数量必须大于0' });
            }
            shopCarData.quantity = quantity;
            
            // 设置用户ID
            shopCarData.userId = ctx.userId;
            
            const result = await shopCarService.createShopCar(shopCarData);
            response.success(ctx, { data: result });
        } catch (err) {
            handleDatabaseError(ctx, err, '添加购物车失败');
        }
    }

    static async updateShopCar(ctx) {
        try {
            const shopCarData = ctx.request.body;
            
            // 验证ID
            if (!shopCarData.id) {
                return response.error(ctx, { message: '缺少购物车项ID' });
            }
            
            // 验证商品数量（如果提供了的话）
            if (shopCarData.quantity !== undefined) {
                const quantity = parseInt(shopCarData.quantity);
                if (isNaN(quantity) || quantity <= 0) {
                    return response.error(ctx, { message: '商品数量必须是大于0的数字' });
                }
                shopCarData.quantity = quantity;
            }
            
            const result = await shopCarService.updateShopCar(shopCarData.id, shopCarData);
            if (result) {
                response.success(ctx, { data: result });
            } else {
                response.error(ctx, { message: '购物车项不存在' });
            }
        } catch (err) {
            handleDatabaseError(ctx, err, '更新购物车失败');
        }
    }
    static async deleteShopCar(ctx) {
        try {
            const { id: shopCarId } = ctx.request.body;
            
            // 验证ID
            if (!shopCarId) {
                return response.error(ctx, { message: '缺少购物车项ID' });
            }
            
            // 验证该购物车项是否属于当前用户
            const shopCarItem = await shopCarService.getShopCarById(shopCarId);
            if (!shopCarItem) {
                return response.error(ctx, { message: '购物车项不存在' });
            }
            
            if (shopCarItem.userId.toString() !== ctx.userId) {
                return response.error(ctx, { message: '无权删除此购物车项' });
            }
            
            const res = await shopCarService.deleteShopCar(shopCarId);
            response.success(ctx, { data: res });
        } catch (err) {
            handleDatabaseError(ctx, err, '删除购物车项失败');
        }
    }

    static async deleteShopCarAll(ctx) {
        try {
            if (!ctx.userId) {
                return response.error(ctx, { message: '请先登录' });
            }
            
            const res = await shopCarService.deleteShopCarAll(ctx.userId);
            response.success(ctx, { data: res });
        } catch (err) {
            handleDatabaseError(ctx, err, '清空购物车失败');
        }
    }

    static async deleteShopCarBySid(ctx) {
        try {
            const { sid } = ctx.request.body;
            
            // 验证sid
            if (!sid) {
                return response.error(ctx, { message: '缺少购物车分组ID' });
            }
            
            const res = await shopCarService.deleteShopCarBySidAndUserId(sid, ctx.userId);
            response.success(ctx, { data: res });
        } catch (err) {
            handleDatabaseError(ctx, err, '删除购物车分组失败');
        }
    }
}
module.exports = ShopCarController;
